﻿using DFGJ.WMS_PDA.WebAPI.Utility.Attributes;
using DFGK_WMS.Context;
using DFGK_WMS.Model.Models;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using System.Reflection;

namespace DFGJ.WMS_PDA.WebAPI.Controllers
{


    [ApiController]
    //[Route("api/[controller]")]
    public class ApiBaseController : ControllerBase
    {
        private readonly DFGK_DB _Context;

        public ApiBaseController(DFGK_DB context)
        {
            _Context = context;
        }

        [NonAction]
        protected bool Log(string message)
        {
            //控制器模块描述
            string apiModule = string.Empty;
            var controllerAttribute = GetType().GetCustomAttribute<HeadAttribute>(false);
            if (controllerAttribute != null)
            {
                apiModule = controllerAttribute._Description;
            }


            //当前登录人
            string currentUserName = HttpContext?.User?.Claims?.FirstOrDefault(t => t.Type == "UserName")?.Value;
            string currentRealName = HttpContext?.User?.Claims?.FirstOrDefault(t => t.Type == "RealName")?.Value;
            string currentJobNo = HttpContext?.User?.Claims?.FirstOrDefault(t => t.Type == "JobNo")?.Value;

            //操作目标
            object? attrbiute = HttpContext.GetEndpoint().Metadata.Where(t => t.GetType().Equals(typeof(FunctionAttribute)))?.FirstOrDefault();
            string actionModule = string.Empty;
            if (attrbiute != null)
            {
                FunctionAttribute? attributeObject = attrbiute as FunctionAttribute;
                actionModule = attributeObject._Description;
            }
            string module = $"[{apiModule}-{actionModule}]";

            TLog log = new TLog()
            {
                CreateDate = DateTime.Now,
                Description = message,
                UserName = currentUserName,
                RealName = currentRealName,
                ModuleName = module,
                LogType = 1,
                UserRemark = currentJobNo,
                ActionType = 0

            };
            _Context.TLogs.Add(log);
            int result = _Context.SaveChanges();
            return result > 0;
        }


    }
}
